import router from './router'
import Performance from '@renderer/utils/performance'

var end = null

// 白名单路由 (无需登录即可访问)
const whiteList = ['/', '/login', '/404']

// 获取本地存储的用户信息
const getUserInfo = () => {
  try {
    const userInfo = localStorage.getItem('userInfo')
    return userInfo ? JSON.parse(userInfo) : null
  } catch (error) {
    console.error('获取用户信息失败:', error)
    return null
  }
}

// 获取JWT Token
const getToken = () => {
  return localStorage.getItem('accessToken')
}

// 验证用户权限
const hasPermission = (userType: string, targetPath: string): boolean => {
  // 权限映射规则
  const permissionMap = {
    'super_admin': ['/admin'],
    'manager': ['/manager'], 
    'worker': ['/worker']
  }
  
  const allowedPaths = permissionMap[userType as keyof typeof permissionMap] || []
  return allowedPaths.some(path => targetPath.startsWith(path))
}

router.beforeEach((to, from, next) => {
  end = Performance.startExecute(`${from.path} => ${to.path} 路由耗时`) /// 路由性能监控
  
  const token = getToken()
  const userInfo = getUserInfo()
  
  // 如果在白名单中，直接放行
  if (whiteList.includes(to.path)) {
    // 如果已登录用户访问登录页，重定向到对应工作台
    if (to.path === '/' || to.path === '/login') {
      if (token && userInfo) {
        const redirectPath = getRedirectPath(userInfo.userType)
        next(redirectPath)
        return
      }
    }
    next()
    return
  }
  
  // 检查是否有token
  if (!token) {
    console.log('未找到访问令牌，重定向到登录页')
    next('/login')
    return
  }
  
  // 检查用户信息
  if (!userInfo) {
    console.log('用户信息不存在，清除token并重定向到登录页')
    localStorage.removeItem('accessToken')
    localStorage.removeItem('refreshToken')
    next('/login')
    return
  }
  
  // 检查用户权限
  if (!hasPermission(userInfo.userType, to.path)) {
    console.log('用户权限不足，重定向到对应工作台')
    const redirectPath = getRedirectPath(userInfo.userType)
    next(redirectPath)
    return
  }
  
  // 权限验证通过，放行
  next()
  
  setTimeout(() => {
    end()
  }, 0)
})

// 根据用户类型获取重定向路径
const getRedirectPath = (userType: string): string => {
  switch (userType) {
    case 'super_admin':
      return '/admin/dashboard'
    case 'manager':
      return '/manager/dashboard'
    case 'worker':
      return '/worker/orders'
    default:
      return '/login'
  }
}

router.afterEach((to) => {
  // 设置页面标题
  const title = to.name as string || 'Cyan-Note管理系统'
  document.title = `${title} - Cyan-Note陪玩订单管理系统`
})
